#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/shm.h>
#include "shmdata.h"
// #include <sys/sem.h>
// #include <sys/types.h>
// #include <sys/stat.h>
// #include <fcntl.h>

int main(void){
    int running =1;
    void *shm=NULL;
    struct shared_use_st *shared =NULL;
    char buffer[BUFSIZ+1];
    int shmid;
    shmid = shmget((key_t)1234,sizeof(struct shared_use_st),0666|IPC_CREAT);
    if (shmid == -1){
        fprintf(stderr,"shmget failed \n");
        exit(EXIT_FAILURE);
    }
    shm = shmat(shmid,(void *)0,0);
    //将共享内存空间连接到当前进程的地址空间
    if(shm ==(void *)-1){
        fprintf(stderr,"shmat failed \n");
        exit(EXIT_FAILURE);
    }
    printf("Memory attached at %p\n",shm);
    shared =(struct shared_use_st *)shm;
    shared->written=0;
    printf("shmid:%d\r\n",shmid);
    while (running){
        if (shared->written == 1){
            printf("read:%s\n",shared->text);
            shared->written=0;
            if (strncmp(shared->text,"end",3)==0)
                running = 0;
        }
        else
            sleep(1);
    }
    shared->written=1;
    printf("I am out while;\r\n");
    if (shmdt(shm)== -1){
        fprintf(stderr,"shmdt failed\n");
        exit(EXIT_FAILURE);
    }
    if(shmctl(shmid,IPC_RMID,0)==-1){
        fprintf(stderr,"shmctl filed \n");
        exit(EXIT_FAILURE);
    }
    exit(EXIT_FAILURE);
}